 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=45 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Implementing Serializable
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='serializable,serialization,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Implementing Serializable</div>

<div class='main-body'>
 
<br><span class='highlight'>Do not implement </i><a href="http://java.sun.com/javase/6/docs/api/java/io/Serializable.html">Serializable</a>
lightly, since it restricts future flexibility, and publicly exposes
class implementation details which are usually private.</span> As well, implementing <tt>Serializable</tt>
correctly is not trivial.

<p>The <tt>serialVersionUID</tt> is a universal version identifier for
a <tt><a href="http://java.sun.com/javase/6/docs/api/java/io/Serializable.html">Serializable</a></tt>
class. Deserialization uses this number to ensure that a loaded class corresponds
exactly to a serialized object. If no match is found, then an <tt><a href="http://java.sun.com/javase/6/docs/api/java/io/InvalidClassException.html">InvalidClassException</a></tt>
is thrown.
<p>Guidelines for <tt>serialVersionUID</tt> :
<ul>
<li>
always include it as a field, for example: "<tt>private static final long
serialVersionUID = 7526472295622776147L;</tt> " include this field even
in the first version of the class, as a reminder of its importance</li>

<li>
do not change the value of this field in future versions, unless you are
knowingly making changes to the class which will render it incompatible
with old serialized objects</li>

<li>
new versions of <tt>Serializable</tt> classes may or may not be able to
read old serialized objects;&nbsp; it depends upon the nature of the change;
provide a pointer to Sun's <a href="http://java.sun.com/javase/6/docs/platform/serialization/spec/version.html#6678">guidelines</a>
for what constitutes a compatible change, as a convenience to future maintainers</li>
</ul>
In Windows, generate <tt>serialVersionUID</tt> using the JDK's graphical tool
like so :
<ul>
<li>
use Control Panel | System | Environment to set the classpath to the correct
directory</li>

<li>
run <tt>serialver -show</tt> from the command line</li>

<li>
point the tool to the class file including the package, for example, <tt>finance.stock.Account</tt>
- without the <tt>.class</tt></li>

<li>
(here are the <tt>serialver</tt> docs for both 
<a href="http://java.sun.com/javase/6/docs/technotes/tools/windows/serialver.html">Win</a>
and <a href="http://java.sun.com/javase/6/docs/technotes/tools/solaris/serialver.html">Unix</a>)</li>
</ul>
<tt>readObject</tt> and<tt> writeObject</tt> :
<ul>
<li>
<tt>readObject</tt> implementations always start by calling default methods</li>

<li>
deserialization must be treated as any constructor : validate the object
state at the end of deserializing - this implies that <tt>readObject</tt>
should almost always be implemented in <tt>Serializable</tt> classes, such
that this validation is performed.</li>

<li>
deserialization must be treated as any constructor :&nbsp; if constructors
make defensive copies for mutable object fields, so must <tt>readObject</tt></li>

<li>
when serializing a <tt>Collection</tt>, store the number of objects in
the
<tt>Collection</tt> as well, and use this number to read them back
in upon deserialization; avoid tricks using <tt>null</tt></li>
</ul>
Other points :
<ul>
<li>
use javadoc's <tt>@serial</tt> tag to denote <tt><a href="http://java.sun.com/javase/6/docs/api/java/io/Serializable.html">Serializable</a></tt>
fields</li>

<li>
the <tt>.ser</tt> extension is conventionally used for files representing
serialized objects</li>

<li>
no <tt>static</tt> or <tt>transient</tt> fields undergo default serialization</li>

<li>
extendable classes should not be <tt>Serializable</tt>, unless necessary</li>

<li>
inner classes should rarely, if ever, implement <tt>Serializable</tt></li>

<li>
container classes should usually follow the style of <tt>Hashtable</tt>,
which implements <tt>Serializable</tt> by storing keys and values, as opposed
to a large hash table data structure</li>
</ul>
<b>Example</b>
<br>
<PRE>

<span class='keyword'>import</span> java.io.Serializable;
<span class='keyword'>import</span> java.text.StringCharacterIterator;
<span class='keyword'>import</span> java.util.*;
<span class='keyword'>import</span> java.io.*;

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> SavingsAccount <span class='keyword'>implements</span> Serializable {

   <span class='comment'>/**
   * This constructor requires all fields to be passed as parameters.
   *
   * @param aFirstName contains only letters, spaces, and apostrophes.
   * @param aLastName contains only letters, spaces, and apostrophes.
   * @param aAccountNumber is non-negative.
   * @param aDateOpened has a non-negative number of milliseconds.
   */</span>
   <span class='keyword'>public</span> SavingsAccount (
     String aFirstName, String aLastName, <span class='keyword'>int</span> aAccountNumber, Date aDateOpened
   ){
      <span class='keyword'>super</span>();
      setFirstName(aFirstName);
      setLastName(aLastName);
      setAccountNumber(aAccountNumber);
      <span class='comment'>//make a defensive copy of the mutable Date passed to the constructor
</span>      setDateOpened( <span class='keyword'>new</span> Date(aDateOpened.getTime()) );
      <span class='comment'>//there is no need here to call validateState.
</span>   }

   <span class='keyword'>public</span> SavingsAccount () {
     <span class='keyword'>this</span> (<span class='literal'>"FirstName"</span>, <span class='literal'>"LastName"</span>, <span class='literal'>0</span>, <span class='keyword'>new</span> Date(System.currentTimeMillis()));
   }

   <span class='keyword'>public</span> <span class='keyword'>final</span> String getFirstName() {
     <span class='keyword'>return</span> fFirstName;
   }

   <span class='keyword'>public</span> <span class='keyword'>final</span> String getLastName(){
     <span class='keyword'>return</span> fLastName;
   }

   <span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>int</span> getAccountNumber() {
     <span class='keyword'>return</span> fAccountNumber;
   }

   <span class='comment'>/**
   * Returns a defensive copy of the field.
   * The caller may change the state of the returned object in any way,
   * without affecting the internals of this class.
   */</span>
   <span class='keyword'>public</span> <span class='keyword'>final</span> Date getDateOpened() {
     <span class='keyword'>return</span> <span class='keyword'>new</span> Date(fDateOpened.getTime());
   }

   <span class='comment'>/**
   * Names must contain only letters, spaces, and apostrophes.
   * Validate before setting field to new value.
   *
   * @throws IllegalArgumentException if the new value is not acceptable.
   */</span>
   <span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>void</span> setFirstName( String aNewFirstName ) {
      validateName(aNewFirstName);
      fFirstName = aNewFirstName;
   }

   <span class='comment'>/**
   * Names must contain only letters, spaces, and apostrophes.
   * Validate before setting field to new value.
   *
   * @throws IllegalArgumentException if the new value is not acceptable.
   */</span>
   <span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>void</span> setLastName ( String aNewLastName ) {
      validateName(aNewLastName);
      fLastName = aNewLastName;
   }

   <span class='comment'>/**
   * Validate before setting field to new value.
   *
   * @throws IllegalArgumentException if the new value is not acceptable.
   */</span>
   <span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>void</span> setAccountNumber( <span class='keyword'>int</span> aNewAccountNumber ) {
      validateAccountNumber(aNewAccountNumber);
      fAccountNumber = aNewAccountNumber;
   }

   <span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>void</span> setDateOpened( Date aNewDate ){
     <span class='comment'>//make a defensive copy of the mutable date object
</span>     Date newDate = <span class='keyword'>new</span> Date( aNewDate.getTime());
     validateDateOpened( newDate );
     fDateOpened = newDate;
   }

   <span class='comment'>// PRIVATE //
</span>
   <span class='comment'>/**
   * The client's first name.
   * @serial
   */</span>
   <span class='keyword'>private</span> String fFirstName;

   <span class='comment'>/**
   * The client's last name.
   * @serial
   */</span>
   <span class='keyword'>private</span> String fLastName;

   <span class='comment'>/**
   * The client's account number.
   * @serial
   */</span>
   <span class='keyword'>private</span> <span class='keyword'>int</span> fAccountNumber;

   <span class='comment'>/**
   * The date the account was opened.
   * @serial
   */</span>
   <span class='keyword'>private</span> Date fDateOpened;

   <span class='comment'>/**
   * Determines if a de-serialized file is compatible with this class.
   *
   * Maintainers must change this value if and only if the new version
   * of this class is not compatible with old versions. See Sun docs
   * for &lt;a href=http://java.sun.com/products/jdk/1.1/docs/guide
   * /serialization/spec/version.doc.html&gt; details. &lt;/a&gt;
   *
   * Not necessary to include in first version of the class, but
   * included here as a reminder of its importance.
   */</span>
   <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>long</span> serialVersionUID = <span class='literal'>7526471155622776147L</span>;

   <span class='comment'>/**
   * Verify that all fields of this object take permissible values; that is,
   * this method defines the class invariant.
   *
   * In this style of implementation, both the entire state of the object
   * and its individual fields can be validated without repeating or
   * duplicating code.
   * Each condition is defined in one place. Checks on the entire
   * object are performed at the end of object construction, and at
   * the end of de-serialization. Checks on individual fields are
   * performed at the start of the corresponding setXXX method.
   * As well, this style replaces the if's and throwing
   * of exceptions at the start of a setXXX, with a simple call to validateXXX.
   * Validation is separated from the regular path of execution,
   * which leads to improved legibility.
   *
   * @throws IllegalArgumentException if any field takes an unpermitted value.
   */</span>
   <span class='keyword'>private</span> <span class='keyword'>void</span> validateState() {
      validateAccountNumber(fAccountNumber);
      validateName(fFirstName);
      validateName(fLastName);
      validateDateOpened(fDateOpened);
   }

   <span class='comment'>/**
   * Ensure names contain only letters, spaces, and apostrophes.
   *
   * @throws IllegalArgumentException if field takes an unpermitted value.
   */</span>
   <span class='keyword'>private</span> <span class='keyword'>void</span> validateName(String aName){
     <span class='keyword'>boolean</span> nameHasContent = (aName != <span class='keyword'>null</span>) &amp;&amp; (!aName.equals(<span class='literal'>""</span>));
     <span class='keyword'>if</span> (!nameHasContent){
       <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Names must be non-null and non-empty."</span>);
     }

     StringCharacterIterator iterator = <span class='keyword'>new</span> StringCharacterIterator(aName);
     <span class='keyword'>char</span> character =  iterator.current();
     <span class='keyword'>while</span> (character != StringCharacterIterator.DONE ){
       <span class='keyword'>boolean</span> isValidChar =
         (Character.isLetter(character) ||
         Character.isSpaceChar(character) ||
         character ==<span class='literal'>'&#092;''</span>
       );
       <span class='keyword'>if</span> ( isValidChar ) {
         <span class='comment'>//do nothing
</span>       }
       <span class='keyword'>else</span> {
        String message = <span class='literal'>"Names can contain only letters, spaces, and apostrophes."</span>;
         <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(message);
       }
       character = iterator.next();
     }
  }

  <span class='comment'>/**
  * AccountNumber must be non-negative.
  * @throws IllegalArgumentException if field takes an unpermitted value.
  */</span>
   <span class='keyword'>private</span> <span class='keyword'>void</span> validateAccountNumber(<span class='keyword'>int</span> aAccountNumber){
      <span class='keyword'>if</span> (aAccountNumber &lt; <span class='literal'>0</span>) {
        String message = <span class='literal'>"Account Number must be greater than or equal to 0."</span>;
        <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(message);
      }
   }

  <span class='comment'>/**
  * DateOpened must be after 1970.
  * @throws IllegalArgumentException if field takes an unpermitted value.
  */</span>
   <span class='keyword'>private</span> <span class='keyword'>void</span> validateDateOpened( Date aDateOpened ) {
     <span class='keyword'>if</span>( aDateOpened.getTime()&lt;<span class='literal'>0</span> ) {
       <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Date Opened must be after 1970."</span>);
     }
   }

   <span class='comment'>/**
   * Always treat de-serialization as a full-blown constructor, by
   * validating the final state of the de-serialized object.
   */</span>
   <span class='keyword'>private</span> <span class='keyword'>void</span> readObject(
     ObjectInputStream aInputStream
   ) <span class='keyword'>throws</span> ClassNotFoundException, IOException {
     <span class='comment'>//always perform the default de-serialization first
</span>     aInputStream.defaultReadObject();

     <span class='comment'>//make defensive copy of the mutable Date field
</span>     fDateOpened = <span class='keyword'>new</span> Date( fDateOpened.getTime() );

     <span class='comment'>//ensure that object state has not been corrupted or tampered with maliciously
</span>     validateState();
  }

    <span class='comment'>/**
    * This is the default implementation of writeObject.
    * Customise if necessary.
    */</span>
    <span class='keyword'>private</span> <span class='keyword'>void</span> writeObject(
      ObjectOutputStream aOutputStream
    ) <span class='keyword'>throws</span> IOException {
      <span class='comment'>//perform the default serialization for all non-transient, non-static fields
</span>      aOutputStream.defaultWriteObject();
    }
} 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction2161-2.html?Id=1'>Type-Safe Enumerations</a> <br>
 
  
  <a href='TopicAction4934-2.html?Id=46'>Singleton</a> <br>
 
  
  <a href='TopicActione102-2.html?Id=70'>Serialization and subclassing</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='45'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=45 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
